'use strict';

// const Controller = require("egg").Controller;
const Controller = require('../core/base_controller');
const BaseController = require('../core/base_controller');
// const FormStream = require('formstream');
const path = require('path');
const fs = require('mz/fs');
const pump = require('mz-modules/pump');
const sendToWormhole = require('stream-wormhole');
/**
 * Controller -   upload
 * @class  upload  单文件上传
 * @class  mutiUpload 多文件上传
 * @author 
 */
class UtilsUploadController extends BaseController {
    async uploadImg() {
        const {
            ctx
        } = this;
        const header = ctx.header;
        const file = ctx.request.files[0];
        if (!file) return ctx.throw(404);
        const env = this.ctx.app.config.env

        try {
            let filename = '',
                targetPath = '';
            let dir = '',
                storyPath = '';
            console.log("==", header.type)
            if (header.type && (header.type == 'WX' || header.type == 'WX2' || header.type == 'ALP' || header.type == 'ALP2')) { //根据type识别传的是微信 还是支付宝二维码
                filename = header.type + '_' + file.filename;
                if (env === 'local') { //开发 
                    dir = path.join(this.config.baseDir, 'app/public', 'pay')
                    storyPath = '/public/pay/' + filename
                } else if (env === 'production' || env === 'prod') { //生产环境
                    dir = path.join(this.config.baseDir, '../public', 'pay')
                    storyPath = '/img/pay/' + filename
                }
            } else { //
                let dayPath = ctx.helper.moment().format('YYYY-MM-DD'); //根据每天日期生成不同的文件夹
                if (env === 'local') { //开发环境 
				
                    if (header.type &&header.type == 'AD'){
						filename = header.type + '_' + file.filename;
                        dir = path.join(this.config.baseDir, 'app/public', 'ad');
                        storyPath = '/public/ad/'+filename;
                    }else{
                        dir = path.join(this.config.baseDir, 'app/public', 'ad');
                        storyPath = '/public/img/ad/'+file.filename ;
                    }
                    console.log(dir,'开发环境',storyPath);
                    
                } else if (env === 'production' || env === 'prod') { //生产环境 
                    // console.log('生产环境');
					 if (header.type &&header.type == 'AD'){
                        filename = header.type + '_' + file.filename;
                        dir = path.join(this.config.baseDir, '../public', 'ad');
                        storyPath = '/img/ad/'+filename;//实际为 ../public/ad/xx.jgp 
                    }else{
						dir = path.join(this.config.baseDir, '../public', 'img'); //nginx指向的是 域名:9000/img/2019/02/28/xxxx.png
                        storyPath = '/img/'+file.filename;
					}                    
                } else {
                    this.fail({}, '没有的环境');
                    return
                }
                let isHaveDir = fs.existsSync(dir)
                if (!isHaveDir) { //不存在则创建
                    await fs.mkdir(dir)
                }
                 if (!header.type){
                   filename = ctx.helper.uuidv1() + path.extname(file.filename).toLowerCase();
                   storyPath = storyPath + filename
				 }
            }
            // console.log("----", dir, filename);
            targetPath = path.join(dir, filename); //  ../public 需要在项目上一级建立这个文件夹
            // console.log(targetPath);
            const source = fs.createReadStream(file.filepath);
            const target = fs.createWriteStream(targetPath);
            try {
                await pump(source, target);
                // ctx.logger.warn('save %s to %s', file.filepath, targetPath);
            } finally { //无论成功/失败都会执行
                // delete those request tmp files
                await ctx.cleanupRequestFiles();
            }
            this.success({
                path: storyPath,  //返回的storyPath 用于web上传数据库
            }, '上传成功');

        } catch (e) {
            console.log(e);
            this.fail({}, '失败,请联系管理员');
        }



    }
    /**
     * 上传单个图片功能 stream流方式 暂保留 
     */
    async upload() {
        const {
            ctx,
            logger
        } = this;
        // const extraParams = await this.parse(ctx.req)
        // console.log("extraParams",extraParams)
        // logger.info('multipleFile, customName, isAjax');
        const stream = await ctx.getFileStream();
        let params = {};

        console.log("上传 图片信息", stream)
        try {
            const header = ctx.header;
            // console.log("==", header.token)
            const isHave = await ctx.model.Token.findAll({
                where: {
                    token: header.token
                }
            });
            if (isHave.length) {
                // console.log("1111111111111",this.ctx.JWT_SECRE_TKEY)  
                //  
                const tokenContent = await ctx.service.functionService.jwtVerify(header.token);
                if (tokenContent) {
                    const name = `img-${ctx.helper.uuidv1()}.${stream.mime.split('/')[1]}`; //            path.basename(stream.filename);
                    const writerStream = fs.createWriteStream(path.join(this.config.baseDir, `app/public/upload/${name}`));
                    stream.pipe(writerStream);
                    params = {
                        "msg": 'upload ok'
                    }
                    this.success(params, 'ok');
                }

            } else {
                console.log("非法")
                this.fail('no');
            }



        } catch (err) {
            //如果出现错误，关闭管道, 必须将上传的文件流消费掉，要不然浏览器响应会卡死
            await sendToWormhole(stream);
            throw err;
        }

    }
    //多图片
    async mutiUpload() {
        let part;
        let result;
        const {
            app,
            ctx
        } = this;
        const parts = ctx.multipart();

        while ((part = await parts()) != null) { //遍历上传的文件
            // console.log("上传测试", part);
            // console.log(part.length, "上传测试", part.fieldname);
            // part 是上传的文件流 
            if (part.length) {
                // 这是 busboy 的字段
                console.log('field: ' + part[0]);
                console.log('value: ' + part[1]);
                console.log('valueTruncated: ' + part[2]);
                console.log('fieldnameTruncated: ' + part[3]);
            } else {
                if (!part.filename) {
                    // 这时是用户没有选择文件就点击了上传(part 是 file stream，但是 part.filename 为空)
                    return this.fail(ctx.ERROR_CODE, '请选择文件');
                }
                // 文件处理，本地环境上传到本地磁盘，生产环境上传到云存储
                try {
                    if (app.config.env === 'production') {
                        // result = await ctx.oss.put('egg-multipart-test/' + part.filename, part);
                        handle(this)
                    } else {
                        handle(this)
                    }
                } catch (err) {
                    // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
                    console.log("上传出错了")
                    await sendToWormhole(part);
                    throw err;
                }
            }
        }

        this.success(result);

        function handle(that) {
            const {
                app,
                ctx
            } = that;
            const fileName = `img-${ctx.helper.uuidv1()}.${part.mime.split('/')[1]}`; //local-upload-image-${ctx.helper.uuidv1()}
            // 创建可写流
            const writerStream = fs.createWriteStream(path.join(that.config.baseDir, `app/public/upload/${fileName}`));

            // 目标写入流
            part.pipe(writerStream);
            result = `public/upload/${fileName}`;
            // console.log("上传ok", that.config.baseDir)
        }
    }

    // ajax上传文件
    async ajaxUpload() { //no
        const {
            ctx
        } = this;
        console.log("===========", 'stream')
        const stream = await ctx.getFileStream();
        console.log("===========", stream)
        const result = await ctx.service.files.ajaxUpload(stream);
        ctx.body = result;
    }
    // buffer上传文件
    async bufferUpload() {
        const {
            ctx
        } = this;
        const stream = await ctx.getFileStream();
        const result = await ctx.service.files.bufferUpload(stream);
        ctx.body = result;
    }
    // form上传文件
    async formUpload() { //ok
        const {
            ctx
        } = this;
        const stream = await ctx.getFileStream();
        const result = await ctx.service.files.formUpload(stream);
        ctx.body = result;
    }
    // multiple上传文件
    async multipleUpload() {
        const {
            ctx
        } = this;
        const parts = ctx.multipart({
            autoFields: true
        });
        const result = await ctx.service.files.multipleUpload(parts);
        ctx.body = result;
    }
    // 文件删除
    async delFile() {//ok
        const {
            ctx,
            config
        } = this;
        // const delMsg = ctx.request.body;
        // const fileUrl = delMsg.fileUrl;
        // const delPath = 'app' + fileUrl.substring(config.imgLocationTruncated);
         let   dir = path.join(this.config.baseDir, 'app/public', 'ad')+"\\1.png";
        console.log(dir,this.config.baseDir);
        // fs.unlink(dir+"/1.png");
        if (fs.existsSync(dir)) {
            fs.unlink(dir);
            ctx.body = 1;
        } else {
            ctx.body = -1;
        }
    }

    async readDir(){//ok

      const dir = await  fs.readdir(this.config.baseDir);
      console.log(">>",dir);
    }
    // 多文件删除 未测
    async delFiles() {
        const {
            ctx,
            config
        } = this;
        const delMsg = ctx.request.body;
        const fileList = delMsg.fileList;
        for (let i = 0; i < fileList.length; i++) {
            const delPath = 'app' + fileList[i].substring(config.imgLocationTruncated);
            if (fs.existsSync(delPath)) {
                fs.unlink(delPath);
            }
        }
        ctx.body = 1;
    }
}

module.exports = UtilsUploadController;